﻿using ArivisAccounts.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace ArivisAccounts.Controllers
{
    [Authorize]
    public class RoleController : Controller
    {
        private UserProfilesDbContext dbContext;

        //
        // GET: /Role/
        public ActionResult Index()
        {
            var model = System.Web.Security.Roles.GetAllRoles().Select(EditRoleModel.Create);
            return View(model);
        }

        //
        // GET: /Role/Create
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Role/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Admin")]
        public ActionResult Create(EditRoleModel roleModel)
        {
            if (ModelState.IsValid)
            {
                Roles.CreateRole(roleModel.Role);
            }
            return RedirectToAction("Index");
        }

        //
        // GET: /Role/Edit/role
        public ActionResult Edit(string role)
        {
            dbContext = new UserProfilesDbContext();

            EditRoleModel model = new EditRoleModel();
            model.Role = role;
            model.UsersInRole = System.Web.Security.Roles.GetUsersInRole(role);
            model.AllUsers = dbContext.UserProfiles.Select(x => x.UserName).ToArray();
            return View(model);
        }

        //
        // POST: /Role/Edit
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Admin")]
        public ActionResult Edit(EditRoleModel roleModel)
        {
            if (ModelState.IsValid)
            {
                string[] oldValues = System.Web.Security.Roles.GetUsersInRole(roleModel.Role);
                string[] newValues = roleModel.UsersInRole ?? new string[0];

                string[] removed = oldValues.Except(newValues).ToArray();
                string[] added = newValues.Except(oldValues).ToArray();

                if (removed.Any())
                    System.Web.Security.Roles.RemoveUsersFromRole(removed, roleModel.Role);
                if (added.Any())
                    System.Web.Security.Roles.AddUsersToRole(added, roleModel.Role);
            }
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (dbContext != null)
                dbContext.Dispose();

            base.Dispose(disposing);
        }
    }
}
